import axios from "axios";
import ElMessage from "element-plus";
import router from "../router";

// 添加请求拦截器
axios.interceptors.request.use(function (config) {
    // 在发送请求之前做些什么
    if (window.sessionStorage.getItem("tokenStr")) {
        config.headers['Authorization'] = window.sessionStorage.getItem("tokenStr");
    }
    return config;
}, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
});

// 添加响应拦截器
axios.interceptors.response.use(function (response) {
    if (response.status && response.status === 200) {
        // 所有失败的情况
        if (response.data.code === 500 || response.data.code === 401) {
            console.log(response.data)
            return;
        }
        if (response.data.message) {
            console.log(response.data)
        }
    }
    return response.data;
}, function (error) {
    // 对响应错误做点什么
    if (error && error.response.status === 500) {
        console.log(error.response.data)
        return;
    }
    if (error.response.data.code === 401) {
        console.log(error.response.data)
        return;
    }
    if (error.response.data.code === 403) {
        console.log(error.response.data)
        return;
    }
    return Promise.reject(error);
});

let baseUrl = '';

// json的 post请求
export const postRequest = (url, params) => {
    return axios({
        method: 'post',
        url: `${baseUrl}${url}`,
        data: params
    })
}

// json的 put请求
export const putRequest = (url, params) => {
    return axios({
        method: 'put',
        url: `${baseUrl}${url}`,
        data: params
    })
}

// json的 get请求
export const getRequest = (url, params) => {
    return axios({
        method: 'get',
        url: `${baseUrl}${url}`,
        data: params
    })
}

// json的 delete
export const deleteRequest = (url, params) => {
    return axios({
        method: 'delete',
        url: `${baseUrl}${url}`,
        data: params
    })
}